package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.admin.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description UserServiceImpl
 * @Author lyh
 * @Date 2024-09-30
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    private static  final String Login_URL="https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 微信小程序登录
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO dto) {
//        1.调用微信接口换取openid
          String openId=getOpenId(dto.getCode());
          if(!StringUtils.hasLength(openId)){
              throw new UserNotLoginException("用户登录失败");
          }
//        2.查询openid是否存在，如果是新用户，需要实现注册功能
           User user=userMapper.selectByOpenId(openId);
          if(user==null){
              user=new User();
              user.setOpenid(openId);
              user.setCreateTime(LocalDateTime.now());
              userMapper.save(user);
          }
//        3.自义定token信息，返回给前端
//如果查询到，根据id生成token，返回给前端
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //查询商家信息
      Merchant merchant= merchantMapper.selectById(1L);
      //配送费计算
        String merLocation= MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal cost = MapUtils.getDelivoryCost(merLocation, dto.getLocation());
        //构建返回值
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .openid(openId)
                .token(token)
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .shopId(1L)
                .shopAddress(merchant.getShopAddress())
                .id(user.getId())
                .deliveryFee(cost)
                .build();
        return userLoginVO;
    }

    @Override
    public User getById(Long id) {
        return userMapper.getById(id);
    }

    @Override
    public void deleteById(Long id) {
        userMapper.deleteById(id);
    }

    private String getOpenId(String code) {
        Map map=new HashMap();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String s = HttpClientUtil.doGet(Login_URL, map);
        Map map1 = JSON.parseObject(s, Map.class);
        return (String) map1.get("openid");
    }
}
